package handel

import (
	"context"
	"order_srv/global"
	pb "order_srv/order"
	"order_srv/types"
	"strconv"
)

type OrderSrvHandel struct {
	pb.UnimplementedOrderServer
}

func NewOrderSrvHandel() *OrderSrvHandel {
	return &OrderSrvHandel{}
}

func (l *OrderSrvHandel) OrderCreate(ctx context.Context, req *pb.OrderCreateReq) (*pb.OrderCreateResp, error) {
	//用户下单时创建订单，接口需验证商品库存并进行相应的库存扣减。
	//分布式锁：使用 Redis 分布式锁确保在高并发情况下库存数据的一致性，避免库存超卖问题。

	stockResult, err := global.RedisClient.Get("GoodsStock" + strconv.Itoa(int(req.GoodsId))).Result()
	if err != nil {
		return nil, err
	}

	numResult, err := global.RedisClient.Get("GoodsNum" + strconv.Itoa(int(req.GoodsId))).Result()
	if err != nil {
		return nil, err
	}

	stock, _ := strconv.Atoi(stockResult)

	num, _ := strconv.Atoi(numResult)

	if stock < num {
		return &pb.OrderCreateResp{
			Code: -1,
			Msg:  "商品库存超卖",
		}, nil
	}

	orders := types.Orders{
		UserId:     int(req.UserId),
		GoodsId:    int(req.GoodsId),
		CountPrice: int(req.CountPrice),
		Discount:   float64(req.Discount),
		SubPrice:   int(req.SubPrice),
		Payment:    int(req.Payment),
	}
	global.Db.Table("orders").Create(&orders)

	return &pb.OrderCreateResp{
		Code: 0,
		Msg:  "订单创建",
	}, nil
}
